package com.wangqingbo.myspringbootproject.service.impl;

import com.wangqingbo.myspringbootproject.dao.SysFileInfoMapper;
import com.wangqingbo.myspringbootproject.entity.SysFileInfo;
import com.wangqingbo.myspringbootproject.service.SysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.UUID;

@Service
public class SysFileServiceImpl implements SysFileService {

    @Autowired
    private SysFileInfoMapper fileInfoMapper;
    @Value("${file.savePath}")
    private String fileSavePath;
    public int saveFileInfo(String moudleId, MultipartFile multipartFile)
    {
        // 原始文件名
        String fileOriginalName = multipartFile.getOriginalFilename();
        String fileSuffix = "";
        if(fileOriginalName.indexOf(".")>-1){
            fileSuffix = fileOriginalName.substring(fileOriginalName.lastIndexOf(".")+1);
        }
        // 生成uuid，替换文件名
        String fileSaveName = UUID.randomUUID().toString().replaceAll("-","") +"."+fileSuffix;
        // 保存路径
        String savedFilePath = fileSavePath;//request.getRealPath("/uploadFiles");
        // type
        String contentType = multipartFile.getContentType();
        // 文件大小
        long fileSize = multipartFile.getSize();
        SysFileInfo fileInfo = new SysFileInfo();
        fileInfo.setFilePath(savedFilePath);
        fileInfo.setFileSize(new BigDecimal(fileSize));
        fileInfo.setFileType(contentType);
        fileInfo.setFileSaveName(fileSaveName);
        fileInfo.setOriginalName(fileOriginalName);
        fileInfo.setSuffix(fileSuffix);
        fileInfo.setModuleId(moudleId);
        // 创建一个文件
        File file = new File(savedFilePath, fileSaveName);
        // 判断是否存在
        if (!file.getParentFile().exists())
        {
            // 创建
            file.getParentFile().mkdirs();
        }
        // 保存文件
        try
        {
            multipartFile.transferTo(file);
        }
        catch (IllegalStateException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        //保存数据到数据库
        int num = fileInfoMapper.saveFileInfo(fileInfo);
        return num;
    }

    @Override
    public SysFileInfo getFileInfoById(String id) {
        return fileInfoMapper.getFileInfoById(id);
    }

}
